﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;

namespace KingSite.Library.Cache.WebCacheWrapper {
    public class WebCacheWrapper : CacheBase, ICache {

        public void Add(string key, object value) {
            Add(key, value, -1);            
        }

        public void Add(string key, object value, int seconds) {
            DateTime now = DateTime.Now.ToUniversalTime();
            CacheItem item;
            if (seconds >= 0) {
                item = new CacheItem(value, now.AddSeconds(seconds));
            }
            else {
                item = new CacheItem(value, now.AddYears(10));
            }
            string hashkey = GetHashKey(key);
            Remove(hashkey);
            HttpContext.Current.Cache[hashkey] = item;            
        }

        public object Get(string key) {
            string hashkey = GetHashKey(key);
            object tmp =HttpContext.Current.Cache[hashkey];
            if (tmp == null) {
                return null;
            }
            CacheItem item = tmp as CacheItem;
            if (item.ExpiryDate <= DateTime.Now.ToUniversalTime()) {
                Remove(key);
                return null;
            }
            return item.Item;
        }

        public void Remove(string key) {            
            string hashkey = GetHashKey(key);
            HttpContext.Current.Cache.Remove(key);
        }

        public void Clear() {
            IDictionaryEnumerator CacheEnum = HttpContext.Current.Cache.GetEnumerator();
            while (CacheEnum.MoveNext()) {
                HttpContext.Current.Cache.Remove(CacheEnum.Key.ToString());
            }
        }
    }
}
